import React, { Component } from 'react'
import './keyMap.css'
import KeyMapJson from './KeyMap.json'
class KeyMap extends Component {
    constructor(props) {
        super(props)
        this.state = {
            keyCode: '',
            lock: false
        }
    }
    componentDidMount() {
        document.addEventListener('keydown', this.onKeyDown)
        document.addEventListener('keyup', this.onKeyUp)
    }
    onKeyDown = (e) => {
        let keyCode = e.key.toUpperCase()
        this.setState({
            keyCode,
            lock: true
        })
    }
    onKeyUp = (e) => {
        let { lock } = this.state
        if (lock) {
            let keyCode = e.key.toUpperCase()
            let len = KeyMapJson.length
            this.setState({
                keyCode: ''
            })
            for (let i = 0; i < len; i++) {
                let arr = KeyMapJson[i]
                let arrLen = arr.length
                for (let j = 0; j < arrLen; j++) {
                    let obj = arr[j];
                    if (obj.key === keyCode) {
                        this.setState({
                            lock: false
                        })
                        obj.url != '' && (window.open(obj.url))
                        break;
                    }
                }
            }
        }
    }
    render() {
        let [keyArr1, keyArr2, keyArr3] = KeyMapJson;
        let { keyCode } = this.state
        return (
            <div className="container">
                <div className="wrap">
                    <ul>
                        {
                            keyArr1.map((item, index) => (
                                <li className={keyCode == item.key ? 'cur' : ''} key={index}>
                                    <span>{item.key}</span>
                                </li>
                            ))
                        }
                    </ul>
                    <ul>
                        {
                            keyArr2.map((item, index) => (
                                <li className={keyCode == item.key ? 'cur' : ''} key={index}>
                                    <span>{item.key}</span>
                                </li>
                            ))
                        }
                    </ul>
                    <ul>
                        {
                            keyArr3.map((item, index) => (
                                <li className={keyCode == item.key ? 'cur' : ''} key={index}>
                                    <span>{item.key}</span>
                                </li>
                            ))
                        }
                    </ul>
                </div>
            </div>
        )
    }
}
export default KeyMap